﻿/* Copyright © 2010 Nolics
Nolics.net and NSQLObjects are trademarks of Nolics.

Microsoft Public License (Ms-PL)

This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.

2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
 */

using System;
using System.Collections.Generic;
using NSQLObjects.Generator.Syntax;

namespace NSQLObjects.Generator.AST
{
    public class Globals
    {

        public Globals() {
            FieldDefaults = new Dictionary<string, DBProperty>(StringComparer.OrdinalIgnoreCase);
            Entities = new Dictionary<string, Entity>(StringComparer.OrdinalIgnoreCase);
            Queries = new Dictionary<string, Query>();
            PassThroughCode = new CommonCode();
            AddBuiltInTypes();
            BaseEntity = "NSQLObjects.Model.BaseEntity";
            BaseQuery = "NSQLObjects.Model.BaseQuery";
            BaseRow = "NSQLObjects.Model.BaseRow";
        }


        /// <summary>
        /// Base class for query
        /// </summary>
        public string BaseQuery { get; set; }

        /// <summary>
        /// Base class for row (updatable)
        /// </summary>
        public string BaseEntity { get; set; }

        /// <summary>
        /// Base class for row (non updatable)
        /// </summary>
        public string BaseRow { get; set; }

        public Dictionary<string, DBProperty> FieldDefaults { get; private set; }

        public Dictionary<string, Entity> Entities { get; private set; }

        public Dictionary<string, Query> Queries { get; private set; }

        public bool ImportMode { get; set; }

        public CommonCode PassThroughCode { get; private set; }

        public string NameSpace { get; set; }

        public string ConnectionString { get; set; }

        public Parser BaseParser { get; set; }

        public string BaseDirectory { get; set; }

        /// <summary>
        /// Get default field type based on column name
        /// </summary>
        /// <param name="name">Column anme</param>
        /// <returns></returns>
        public DBProperty GetDefault(string name) {
            if (FieldDefaults.ContainsKey(name))
                return FieldDefaults[name];
            return null;
        }

        /// <summary>
        /// Get default field type based on column SQL datatype
        /// </summary>
        /// <param name="typeName">SQL type name for column</param>
        /// <returns></returns>
        public DBProperty GetDefaultForType(string typeName) {
            if (FieldDefaults.ContainsKey(TypePrefix + typeName))
                return FieldDefaults[TypePrefix + typeName];
            if (FieldDefaults.ContainsKey(BuiltInPrefix + typeName))
                return FieldDefaults[BuiltInPrefix + typeName];
            return null;
        }

        /// <summary>
        /// Prefix for user defined type mapping
        /// </summary>
        public const string TypePrefix = "$Type$";

        /// <summary>
        /// Prefix for built in type mapping
        /// </summary>
        public const string BuiltInPrefix = "$BuiltIn$";

        public string TrimBlock(string block) {
            return block.TrimStart('[').TrimEnd(']');
        }

        public string TrimString(string p) {
            return p.Trim('"');
        }

        public void Import(string filename) {
            bool oldImportMode = ImportMode;
            try {
                ImportMode = true;
                Scanner sc = new Scanner(BaseDirectory + "\\" + filename);
                Parser pr = new Parser(sc);
                pr.errors.ReportErrors = BaseParser.errors.ReportErrors;
                pr.errors.FileName = filename;
                pr.G = this;
                pr.Parse();
            } finally {
                ImportMode = oldImportMode;
            }
        }

        /// <summary>
        /// Add built in type defaults
        /// </summary>
        private void AddBuiltInTypes() {
            AddBuiltIn("varchar", "string");
            AddBuiltIn("nvarchar", "string");
            AddBuiltIn("text", "string");
            AddBuiltIn("ntext", "string");
            AddBuiltIn("char", "string");
            AddBuiltIn("nchar", "string");
            AddBuiltIn("date", "DateTime");
            AddBuiltIn("datetime", "DateTime");
            AddBuiltIn("uniqueidentifier", "Guid");
            AddBuiltIn("bit", "bool");
            AddBuiltIn("short", "int");
            AddBuiltIn("int", "int");
            AddBuiltIn("bigint", "long");
            AddBuiltIn("float", "double");
            AddBuiltIn("real", "double");
            AddBuiltIn("decimal", "decimal");
            AddBuiltIn("varbinary", "byte[]");
            AddBuiltIn("image", "byte[]");
        }

        private void AddBuiltIn(string sqltypename, string cstypename) {
            FieldDefaults.Add(BuiltInPrefix + sqltypename, new DBProperty(sqltypename) { TypeName = cstypename });
        }
    }

}
